"""
文件名: parse_dat_to_csv.py

描述:
这个脚本用于将 IBC（惯性/北斗组合）导航系统的原始数据文件（.dat 或 .TXT 格式）转换为 CSV 格式。
它读取二进制导航数据，解析融合数据和原始数据，然后将这些数据写入一个新的 CSV 文件。

主要功能:
1. 读取二进制导航数据文件
2. 使用 IBCNav 类解析数据
3. 将解析后的数据写入 CSV 文件，包括融合数据和原始数据
4. 自动生成包含时间戳的输出文件名，并将输出文件保存在与输入文件相同的目录中

使用方法:
1. 确保 python_lib.ibc_nav 模块可用，其中包含 IBCNav 类
2. 在 main 函数中设置正确的输入文件路径
3. 运行脚本

主要函数:
- parse_dat_to_csv(input_file, output_file): 
  解析输入的 .dat 或 .txt 文件并将数据写入 CSV 文件

- main(): 
  设置输入文件路径，生成输出文件名，并调用 parse_dat_to_csv 函数

注意事项:
- 输入文件应为二进制格式（.dat 或 .TXT）
- 确保对输入文件所在目录有写入权限
- 输出的 CSV 文件将包含 "Data_Type" 列，标识每行数据是融合数据还是原始数据

依赖:
- csv 模块
- os 模块
- datetime 模块
- python_lib.ibc_nav 模块（自定义模块，包含 IBCNav 类）

作者: [IBC-kishs]
创建日期: [24-7-10]
最后修改日期: [25-6-16]
版本: 1.1
"""

'''
pyinstaller -F -w -i ./IBC.ico --add-data "./IBC.ico;." --add-data "./python_lib;python_lib" sample\win\python\parse_dat_to_csv.py
'''

import csv
import sys
import os
import tkinter as tk
from datetime import datetime
from tkinter import filedialog, messagebox

# 现在你可以导入 ibc_nav 模块
from python_lib.ibc_nav import IBCNav

def parse_dat_to_csv(input_file, output_file):
    nav = IBCNav()
    
    with open(input_file, 'rb') as dat_file, open(output_file, 'w', newline='') as csv_file:
        csv_writer = csv.writer(csv_file)
        
        # Write headers
        fusion_keys = list(nav.get_fusion_keys())
        origin_keys = list(nav.get_origin_keys())
        csv_writer.writerow(['Data_Type'] + fusion_keys + origin_keys)
        
        # Read and process data
        while True:
            # 每次读一个字节数据
            chunk = dat_file.read(1)
            if not chunk:
                break
            
            if nav.push_data(chunk[0]):
                fusion_update, origin_update = nav.get_update_flag()
                
                if fusion_update:
                    _, fusion_data = nav.get_fusion_data()
                    row = ['Fusion'] + [fusion_data.get(key, '') for key in fusion_keys] + [''] * len(origin_keys)
                    csv_writer.writerow(row)
                
                if origin_update:
                    _, origin_data = nav.get_origin_data()
                    row = ['Origin'] + [''] * len(fusion_keys) + [origin_data.get(key, '') for key in origin_keys]
                    csv_writer.writerow(row)

def select_file():
    file_path = filedialog.askopenfilename(
        title="选择 二进制文件",
        filetypes=[("DAT Files", "*.dat"), ("TXT Files", "*.txt"), ("All Files", "*.*")]
    )
    if file_path:
        input_entry.delete(0, tk.END)
        input_entry.insert(0, file_path)

def drop_file(event):
    file_path = event.data.strip('{}')  # 去除可能的花括号（Windows路径）
    if os.path.isfile(file_path) and (file_path.lower().endswith('.dat') or file_path.lower().endswith('.txt')):
        input_entry.delete(0, tk.END)
        input_entry.insert(0, file_path)
    else:
        messagebox.showwarning("警告", "请选择有效的 .dat 或 .txt 文件")

def start_processing():
    input_file = input_entry.get()
    if not os.path.isfile(input_file):
        messagebox.showerror("错误", "请输入有效的文件路径")
        return

    input_dir = os.path.dirname(os.path.abspath(input_file))
    input_filename = os.path.splitext(os.path.basename(input_file))[0]
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    output_filename = f"{input_filename}_{timestamp}.csv"
    output_file = os.path.join(input_dir, output_filename)

    print(f"Parsing {input_file} to {output_file}")
    parse_dat_to_csv(input_file, output_file)
    print(f"Parsed {input_file} to {output_file}")
    messagebox.showinfo("解析完成", f"文件已成功保存至:\n{output_file}")

def get_icon():
    import base64
    ibc_base64 = "AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAD+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/9/Pr//fDg//3my//948L//eTE//3q0v/99On//f39//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//358v/93LP//cB2//2sSP/9qEH//qlB//6pQf/+qUH//qlB//2oQf/9rk7//cF2//3Uof/97Nf//f39//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//379//906D//a1L//6pQf/+qUH//qlB//6pQf/+qUH//qlB//6pQf/+qUH//qlB//6pQf/+qUH//qlB//2oQf/9t2L//dqw//369f/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/98OD//bZf//6pQf/+qUH//qlB//6pQP/9q0b//bdi//3AdP/9wnr//cB1//25ZP/9rUv//ahB//6pQf/+qUH//qlB//6pQf/+qUH//a9O//3Tn//9+PH//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//e/d//2vT//+qUH//qlB//2uTf/9zZP//enR//38+f/+/v7//v7+//7+/v/+/v7//v7+//39/f/98uT//d64//3Gg//9rUz//qlA//6pQf/+qUH//qlB//2uTf/92Kr//fz6//7+/v/+/v7//v7+//7+/v/+/v7//v7+//358//9tFr//qlB//2qRf/90Zz//fnz//3+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v79//37+P/94b7//b9z//2pQv/+qUH//qlB//2pQf/9uWX//fDg//7+/v/+/v7//v7+//7+/v/+/v7//c2S//6pQf/9sFH//ezW//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/9/f3//fDh//3KjP/9qkX//qlB//zUof/98uT//v7+//7+/v/+/v7//v7+//316//9q0X//a1K//zdtv/98OD//fXr//39/f/+/v7//fHi//3w4P/99ev//fv5//359P/99ez//f39//7+/v/+/v7//v7+//379//96dD//erT//3v3f/99Oj//fv4//3y5P/9xH7//bVd//38+v/+/v7//v7+//7+/v/+/v7//diq//6pQf/92q7//bJV//2pQf/9qEH//fjx//7+/v/9x4T//ahB//2oQf/9vW7//axI//2pQf/9yIf//f39//7+/v/+/v7//cN7//2pQf/+qUH//ahB//2oQf/9q0b//dir//39/f/948L//OHA//7+/v/+/v7//v7+//7+/v/9wXf//bFU//38+v/9umf//qlB//6pQf/98OD//v7+//3Plv/+qUH//qlB//6pQf/+qUH//qlB//6oQf/94b///v7+//7+/v/9sVP//qlB//6pQf/+qUH//qlB//6pQf/9q0b//fjy//7+/v/9+vf//v7+//7+/v/+/v7//v7+//2xU//9zI///v7+//3BeP/+qUH//qlB//3ozv/+/v7//deo//6pQf/+qUH//alB//2qRP/+qUH//qlB//3Efv/+/v7//v7+//2zV//+qUH//qlB//3Eff/9q0f//qlB//6pQf/848P//f37//3x4//99u3//v7+//7+/v/9/fz//alC//3dtf/+/v7//cmK//6pQf/+qUH//eC9//7+/v/937r//qlB//6pQf/9t2L//dyz//6pQf/+qUH//bRa//7+/v/+/v7//btp//6pQf/+qUH//d65//27av/+qUH//qlB//3csv/8zZH//enR//3Plv/+/v7//v7+//38+v/9qUH//eTG//7+/v/90Zv//qlB//6pQf/92Kv//v7+//3nzf/+qUH//qlB//2zV//96dH//qlB//6pQf/9q0X//f39//7+/v/9w3z//qlB//6pQf/91qf//cR+//6pQf/+qUH//dSi//3hvv/9rEj//a9P//38+f/+/v7//f39//2sSf/95MT//v7+//3Zrf/+qUH//qlB//3Qmf/+/v7//fDf//6pQf/+qUH//atF//3y4//+qUH//qlB//2oQf/99+7//v7+//3Ljv/+qUH//qlB//3OlP/92rD//b9z//26aP/91aP//fz6//2vT//+qUD//efM//7+/v/+/v7//bll//3cs//+/v7//eG///6pQf/+qUH//cmI//7+/v/9+PH//ahB//6pQf/+qUH//fPo//2pQf/+qUH//alB//3u3P/+/v7//dSg//6pQf/+qUH//caC//7+/v/+/v7//f3+//39/f/+/v7//caC//6pQf/906D//v7+//7+/v/9y47//c6U//7+/v/96dD//qlB//6pQf/9wXb//v7+//39/f/9q0f//qlB//6pQf/97tv//a5N//6pQf/+qUH//ebJ//7+/v/93LP//qlB//6pQf/9vW///v7+//7+/v/+/v7//v7+//7+/v/916j//qlB//3Ggv/+/v7//v7+//3kxf/9u2r//v7+//3x4v/+qUH//qlB//25Zf/+/v7//f3+//2zWf/+qUH//qlB//3lyP/9t2D//qlB//6pQf/93bX//v7+//3kxf/+qUH//qlB//21Xf/97dn//cR+//3Jif/90p7//f3+//3hvv/+qUH//b1v//7+/v/+/v7//fz6//2yVv/9+fP//fnz//2oQf/+qUH//bFT//39/f/+/v7//bxr//6pQf/+qUH//duy//2+cP/+qUH//qlB//3Vo//+/v7//ezY//6pQf/+qUH//a1K//3t2v/+qUH//qlB//2rRv/9/f3//eXG//6pQf/9umj//v7+//7+/v/+/v7//dSj//3fuv/9/f3//axI//6pQf/9qkP//f38//7+/v/9xH3//qlB//6pQf/9s1j//a1L//6pQf/+qUH//c6V//7+/v/99uz//ahB//6pQf/9qEH//Nep//6pQf/+qUH//ahB//348f/94b///qlB//29bf/+/v7//v7+//7+/v/9+fT//caE//3+/f/9tFr//qlB//6pQf/99u3//v7+//3MkP/+qUH//qlB//6pQf/+qUH//qlB//6pQf/90pz//v7+//39/f/9sVP//qlB//6pQf/+qUH//qlB//6pQf/+qUH//fPn//3Xp//+qUH//cR+//7+/v/+/v7//v7+//7+/v/94Lz//e3Z//28a//+qUH//qlB//3u2//+/v7//dSi//6pQf/+qUH//a9O//2qQ//+qUH//alB//3ny//+/v7//v7+//3XqP/9qUH//qlB//6pQf/+qUH//qlB//2sSP/9+/f//cV///6pQf/91KH//v7+//7+/v/+/v7//v7+//39/f/83bb//OvW//3gvf/927H//fTp//7+/v/93bT//qlB//6pQf/9umf//e7a//3Snf/937r//f39//7+/v/+/v7//f39//3t2P/937r//dqv//3Wpf/90p7//enP//369v/9rUv//alB//3r1P/+/v7//v7+//7+/v/+/v7//v7+//359P/06N//amf8/25r/P/9/v3//v7+//3lx//+qUH//qlB//2xVP/9/f3//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//duw//6pQf/9tl7//f39//7+/v/+/v7//v7+//7+/v/+/v7//v7+//Tx+P8XE/3/Mi79//z8/f/+/v7//e3Z//6pQf/+qUH//apD//39+//+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//348f/9sVP//alB//3euP/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7/oJ/8/xoW/f8gG/3/vbz8//7+/v/99ev//qlB//6pQf/9qUH//fbs//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/9/fv//cJ6//6pQf/9vW7//f38//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7/oJ/9/8bF/f/88OH//fLl//38+//9w3z//b5x//25Zv/98eH//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//fv4//3Gg//9qEH//bJV//306P/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/y8v3//f39//79/f/958z//NGb//3s1v/9/f3//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//f3+//3r1f/9uWX//qlB//20Wf/98eL//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/9+fT//dKd//y5Zv/9zJD//d+7//3u3P/9+fP//f39//39/f/9+/j//e/d//3asP/9vnD//alB//2pQf/9xoP//ffw//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//fr1//3et//9w3v//a5N//2oQf/9qkX//axI//2pQv/+qUH//ahB//2vUP/9yYr//e3Y//39/f/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/9/f3//fPm//3pz//948T//ePD//3nzP/98uT//f39//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
    # 存储icon
    byte_data = base64.b64decode(ibc_base64)
    with open('IBC.ico', 'wb') as icon_file:
        icon_file.write(byte_data)

    return 'IBC.ico'


if __name__ == "__main__":
    # 创建主窗口
    root = tk.Tk()
    root.title("IBC_NAV解析软件 V1.1")
    # 窗口图标
    root.iconbitmap(default=get_icon())

    root.resizable(False, False)
    root.geometry("500x200")

    # 输入框和按钮
    tk.Label(root, text="需要解析的 .dat 或 .txt 文件路径:").pack(pady=5)
    input_entry = tk.Entry(root, width=50)
    input_entry.pack(pady=5)

    tk.Button(root, text="选择需要解析的二进制数据...", command=select_file).pack(pady=5)
    tk.Button(root, text="开始处理", command=start_processing).pack(pady=10)

    # 启动 GUI 主循环
    root.mainloop()
